'use strict';

const Service = require('egg').Service
const Api = require('../api/api.json')

class HandleRequsetService extends Service {
  /**
   * 数据请求
   */
  async requestDate() {
    const that = this
      , ctx = that.ctx
      , Config = that.config
      , token = ctx.cookies.get('accessToken')
      , options = ctx.state.httpOption
      , headers = { 'access-token': token || "", 'content-type': 'text/html;charset=utf-8' };

    let url = await that.handleReqireApi(options.url);
    if (!options.outApi) url = Config.baseUrl + url;
    that.logger.info('<<<<<< start >>>>>>>') 
    that.logger.info(url) //打印链接
    that.logger.info(options.data) // 传参
    try {
      const res = await ctx.curl(url, {
        method: options.method || 'get',
        data: options.data || {},
        timeout: Config.timeout,
        dataType: 'json',
        headers: Object.assign(headers, options.headers || {})
      })

      that.logger.info(res.data)
      ctx.status = res.status;
      if (res.status === 200 && res.data) {
        ctx.state.result = res;
        if (res.data.status !== 200 && !options.noLocal && (typeof options.ignoreError === 'undefined' || !options.ignoreError)) {
          that.logger.warn(`data error: ${res.data.message} `);
          res.status = res.data.status;
        }
        else {
          that.logger.warn(`request success`);
        }
      }
      else {
        that.logger.error(`response status is not 200:${url}`);
        ctx.state.result.data = {
          status: 402,
          message: '请求失败'
        }
      }

    } catch (error) {
      that.logger.error(err);
    }
     
  }
  /**
   * 获取配置的接口地址
   * @param {Array} urlArr 接口配置信息
   */
  async handleReqireApi(urlArr) {
    let targetApi = Api;
    for (let i = 0; i < urlArr.length; i++) {
      targetApi = targetApi[urlArr[i]];
    }
    return targetApi;
  }
  
}

module.exports = HandleRequsetService;